package cn.ryanpenn.es.springclound.service.impl;

import cn.ryanpenn.es.springclound.model.WeatherResponse;
import cn.ryanpenn.es.springclound.service.WeatherService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * WeatherServiceImpl
 *
 * @author pennryan
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    private final String WEATHER_BYNAME_API = "http://wthrcdn.etouch.cn/weather_mini?city=";
    private final String WEATHER_BYKEY_API = "http://wthrcdn.etouch.cn/weather_mini?citykey=";

    @Autowired
    OkHttpClient okHttpClient;

    @Override
    public WeatherResponse getByCityCode(int code) {
        return queryWeather(WEATHER_BYKEY_API + code);
    }

    @Override
    public WeatherResponse getByCityName(String name) {
        return queryWeather(WEATHER_BYNAME_API + name);
    }

    private WeatherResponse queryWeather(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if (body != null) {
                return new ObjectMapper().readValue(body.string(), WeatherResponse.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
